// @Title  登录、注册
// @Description  登录注册路由承接
// @Author  xueneng
package v1

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mycms/global"
	"mycms/model/common"
	"mycms/model/common/response"
	"mycms/model/system"
	systemReq "mycms/model/system/request"
	systemRes "mycms/model/system/response"
	"mycms/service/admin"
	commonService "mycms/service/common"
	"mycms/utils"
)


// @Tags 后台接口
// @Summary 后台登录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param username formData string true "帐号"
// @Param password formData string true "密码"
// @Param captcha formData string true "验证码"
// @Param key_id formData string true "验证码ID"
// @Success 200 {object} systemRes.AdminLoginResponse
// @Router /admin/v1/login [post]
// @auth      xueneng
func (b *BaseApi)Login (c *gin.Context) {
	var param systemReq.Login
	err := c.BindJSON(&param)

	if err != nil{
		//	返回错误信息
		response.FailWithMessage(err.Error(), c)
		return
	}

	//	验证参数是否合法
	if valErr := commonService.Validate.Struct(param); valErr != nil{
		response.FailWithMessage(commonService.Translate(valErr, param), c)
		return
	}

	verify := commonService.VerifyCaptcha(param.KeyId, param.Captcha)

	if verify == false{
		//	验证码错误
		response.FailWithMessage("验证码不正确！", c)
		return
	}

	//	组装数据
	User := system.Admin{
		Username: param.Username,
		Password: param.Password,
	}

	errs, res := admin.Login(User)
	if errs != nil {
		global.LOG.Error("登录失败!", zap.Error(errs))
		response.FailWithDetailed(systemRes.SysAdminResponse{Admin: res}, "登录失败，帐号或密码错误！", c)
	} else {
		j := &commonService.JWT{SigningKey: []byte(global.CONFIG.Jwt.SigningKey)} // 唯一签名
		claims := j.CreateClaims(common.BaseClaims{
			UUID:        res.Uuid,
			ID:          res.ID,
			Realname:    res.Realname,
			Username:    res.Username,
			RoleId:      res.RoleId,
			//AuthorityId: res.AuthorityId,
		})

		token, err := j.CreateToken(claims)
		if err != nil {
			global.LOG.Error("获取token失败!", zap.Error(err))
			response.FailWithMessage("获取token失败", c)
			return
		}
		response.OkWithDetailed(systemRes.AdminLoginResponse{
			Uuid:      res.Uuid,
			Username:  res.Username,
			Token:     token,
			ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
		}, "登录成功", c)
	}

}


// @Tags 后台接口
// @Summary 获取验证码
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.CaptchaResponse
// @Router /admin/v1/captcha [get]
// @auth      xueneng
func (b *BaseApi)GetCaptcha(c *gin.Context) {
	id, b64s, err := commonService.GetCaptcha()

	if err != nil {
		global.LOG.Error("验证码获取失败!", zap.Error(err))
		response.FailWithMessage("验证码获取失败", c)
	}else {
		res := response.CaptchaResponse{
			CaptchaId:     id,
			PicPath:       b64s,
			CaptchaLength: global.CONFIG.Captcha.KeyLong,
		}
		response.OkWithDetailed(res, "验证码获取成功", c)
	}
}


// @Tags 后台接口
// @Summary 获取用户信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {object} response.CaptchaResponse
// @Router /admin/v1/userInfo [get]
// @auth      xueneng
func (b *BaseApi)GetUserInfo(c *gin.Context)  {

	UserId := utils.GetUserID(c)
	User := global.Model{ID: UserId}

	errs, res := admin.GetUserInfo(User)

	if errs != nil {
		global.LOG.Error("获取用户信息失败!", zap.Error(errs))
		response.FailWithDetailed(systemRes.SysAdminResponse{Admin: res}, "获取用户信息失败！", c)
	} else {
		//	把逗号分隔的字符串转换成int切片
		RolesId := commonService.StringToInt(res.RoleId, ",")

		response.OkWithDetailed(systemRes.AdminInfoResponse{
			Uuid:      res.Uuid,
			Username:  res.Username,
			Roles:     RolesId,
		}, "查询成功", c)
	}

}

// @Tags 后台接口
// @Summary 退出登录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"code":0,"data":{},"msg":"退出成功"}"
// @Router /admin/v1/userinfo [get]
// @auth      xueneng
func (b *BaseApi)Logout(c *gin.Context)  {
	c.Set("claims", "")
	response.OkWithMessage("退出成功", c)
}


// @Tags 后台接口
// @Summary 管理员列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"code":0,"data":{},"msg":"查询成功"}"
// @Router /admin/v1/adminList [get]
// @auth      xueneng
func (b *BaseApi)GetAdminLists(c *gin.Context)  {
	var pageInfo systemReq.SearchAdminParams

	if ok := c.Bind(&pageInfo); ok != nil{
		//	返回错误信息
		response.FailWithMessage(ok.Error(), c)
		return
	}

	err, list, total := admin.GetAdminLists(pageInfo)

	if err != nil{
		global.LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	}else{
		response.OkWithDetailed(response.PageResult{
			List:   list,
			Total:  total,
			Page:   pageInfo.Page,
			Limit:  pageInfo.Limit,
		}, "查询成功", c)
	}

}


// @Tags 后台接口
// @Summary 管理员详情
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param id formData string true "管理员ID"
// @Success 200 {string} string "{"code":0,"data":{},"msg":"查询成功"}"
// @Router /admin/v1/adminInfo [get]
// @auth      xueneng
func (b *BaseApi)GetAdminInfo(c *gin.Context)  {
	var param systemReq.AdminInfoParams
	err := c.Bind(&param)

	if err != nil{
		//	返回错误信息
		response.FailWithMessage(err.Error(), c)
		return
	}

	//	验证参数是否合法
	if valErr := commonService.Validate.Struct(param); valErr != nil{
		response.FailWithMessage(commonService.Translate(valErr, param), c)
		return
	}

	User := global.Model{ID: param.Id}

	errs, res := admin.GetUserInfo(User)

	if errs != nil {
		global.LOG.Error("获取失败!", zap.Error(errs))
		response.FailWithDetailed(systemRes.SysAdminResponse{Admin: res}, "获取失败！", c)
	} else {
		//	把逗号分隔的字符串转换成int切片
		var RolesId []int
		if res.RoleId != ""{
			RolesId = commonService.StringToInt(res.RoleId, ",")
		}

		response.OkWithDetailed(systemRes.AdminInfoResponse{
			Id:       	res.ID,
			Username:   res.Username,
			Status:  	res.Status,
			Phone:  	res.Phone,
			Email:  	res.Email,
			Realname: 	res.Realname,
			Remark:  	res.Remark,
			Roles:      RolesId,

		}, "查询成功", c)
	}
}



// @Tags 后台接口
// @Summary 添加管理员
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"code":0,"data":{},"msg":"退出成功"}"
// @Router /admin/v1/adminCreate [get]
// @auth      xueneng
func (b *BaseApi)CreateAdmin(c *gin.Context)  {
	var param systemReq.CreateAdminParams
	err := c.BindJSON(&param)

	if err != nil{
		//	返回错误信息
		response.FailWithMessage(err.Error(), c)
		return
	}

	//	验证参数是否合法
	if valErr := commonService.Validate.Struct(param); valErr != nil{
		response.FailWithMessage(commonService.Translate(valErr, param), c)
		return
	}

	user := &system.Admin{
		Username: param.Username,
		Password: param.Password,
		Realname: param.Realname,
		Status:   param.Status,
		Remark:   param.Remark,
		Phone:    param.Phone,
		Email:    param.Email,
		//RoleId:   param.RoleId,
	}
	errs := admin.CreateAdmin(*user)

	if errs != nil {
		global.LOG.Error("新增失败!", zap.Error(errs))
		response.FailWithDetailed("", "新增失败："+errs.Error(), c)
	} else {
		response.OkWithDetailed("", "新增成功", c)
	}
}


// @Tags 后台接口
// @Summary 编辑管理员
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"code":0,"data":{},"msg":"退出成功"}"
// @Router /admin/v1/adminEdit [get]
// @auth      xueneng
func (b *BaseApi)UpdateAdmin(c *gin.Context)  {
	var param systemReq.UpdateAdminParams
	err := c.BindJSON(&param)

	if err != nil{
		//	返回错误信息
		response.FailWithMessage(err.Error(), c)
		return
	}

	//	验证参数是否合法
	if valErr := commonService.Validate.Struct(param); valErr != nil{
		response.FailWithMessage(commonService.Translate(valErr, param), c)
		return
	}

	errs := admin.UpdateAdmin(param)

	if errs != nil {
		global.LOG.Error("保存失败!", zap.Error(errs))
		response.FailWithDetailed("", "保存失败！", c)
	} else {
		response.OkWithDetailed("", "保存成功", c)
	}
}


// @Tags 后台接口
// @Summary 删除管理员
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"code":0,"data":{},"msg":"退出成功"}"
// @Router /admin/v1/adminDel [get]
// @auth      xueneng
func (b *BaseApi)DelAdmin(c *gin.Context)  {
	var param systemReq.AdminDelParams
	err := c.Bind(&param)

	if err != nil{
		//	返回错误信息
		response.FailWithMessage(err.Error(), c)
		return
	}

	//	验证参数是否合法
	if valErr := commonService.Validate.Struct(param); valErr != nil{
		response.FailWithMessage(commonService.Translate(valErr, param), c)
		return
	}

	errs := admin.DelAdmin(param)

	if errs != nil {
		global.LOG.Error("新增失败!", zap.Error(errs))
		response.FailWithDetailed("", "新增失败："+errs.Error(), c)
	} else {
		response.OkWithDetailed("", "新增成功", c)
	}
}
